﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Tododoo.Lib;
using Tododoo.Data;
using System.Windows.Input;

namespace Tododoo.ViewModels
{
    public class AddThingViewModel : ViewModelBase
    {
        public static readonly Mail NewThingAdded = new Mail("NewThingAdded");

        private IData _database;
        private string _newItemText;
        private ICommand _addNewItemCommand;
        private ICommand _cancelCommand;

        public AddThingViewModel()
        {
            this._database = Services.Get<IData>();
        }

        public string NewItemText
        {
            get { return this._newItemText; }
            set
            {
                this._newItemText = value;
                OnPropertyChanged("NewItemText");
            }
        }

        #region AddNewItemCommand

        public ICommand AddNewItemCommand
        {
            get
            {
                return this._addNewItemCommand ??
                    (this._addNewItemCommand = new RelayCommand(
                        this.AddNewItemCommandExecuted,
                        this.AddNewItemCommandCanExecute));
            }
        }

        private void AddNewItemCommandExecuted(object param)
        {
            Thing newThing = Thing.CreateThing(Guid.NewGuid(), NewItemText, false, DateTime.Now);
            this._database.AddThing(newThing);
            this._database.Save();
            PostOffice.Send(NewThingAdded, newThing);
            this.Close();
        }

        private bool AddNewItemCommandCanExecute(object param)
        {
            return !string.IsNullOrWhiteSpace(NewItemText);
        }

        #endregion

        #region CancelCommand

        public ICommand CancelCommand
        {
            get
            {
                return this._cancelCommand ??
                    (this._cancelCommand = new RelayCommand(
                        (o) => this.Close()));
            }
        }

        #endregion
    }
}
